/**
 * 在这里定义与待办事项相关的路由处理函数，供/router/tasks.js模块使用
 */

// 导入db模块
const db = require('../db/index')
// 导入util模块
const util = require('util')
// 将db.query方法转换为promise
const query = util.promisify(db.query).bind(db)

// 获取分类列表接口
exports.getClassifications = async (req, res) => {
  const { user_id } = req.query
  console.log('传到后端的user_id:', user_id)
  const sql = 'SELECT * FROM classification WHERE user_id = ?'
  try {
    const result = await query(sql, [user_id])
    console.log('获取分类列表result:', result)
    res.send({
      status: 0,
      message: '获取分类列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取分类列表失败',
      error: err.message
    })
  }
}

// 添加分类接口
exports.addClassification = async (req, res) => {
  const { classify_name, user_id } = req.body
  const sql = 'INSERT INTO classification (classify_name, user_id) VALUES (?, ?)'
  try {
    const result = await db.query(sql, [classify_name, user_id])
    res.send({
      status: 0,
      message: '添加分类成功',
      data: {
        id: result.insertId,
        classify_name,
        user_id
      }
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '添加分类失败',
      error: err.message
    })
  }
}

// 删除分类接口:删除这个分类,并把这个分类下的所有待办任务的isDeleted设置为true
exports.deleteClassification = async (req, res) => {
  console.log('删除分类接口')
  const { id } = req.params
  console.log('删除分类的id:', id)
  // 软删除任务：将任务的 isDeleted 字段设置为 true
  const deleteTasksSql = 'UPDATE task SET isDeleted = 1 WHERE classify_id = ?'
  // 彻底删除分类
  const deleteClassificationSql = 'DELETE FROM classification WHERE id = ?'
  try {
    await query(deleteTasksSql, [id])
    await query(deleteClassificationSql, [id])
    res.send({
      status: 0,
      message: '删除分类成功'
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '删除分类失败',
      error: err.message
    })
  }
}

// 获取今日任务列表接口
exports.getTodayTasks = async (req, res) => {
  const { user_id } = req.query
  // 获取今天的日期，格式 YYYY-MM-DD
  const today = new Date().toISOString().split('T')[0]
  const sql = 'SELECT * FROM task WHERE user_id = ? AND isDeleted = 0 AND finish_date = ?'
  try {
    const result = await query(sql, [user_id, today])
    res.send({
      status: 0,
      message: '获取今日任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取今日任务列表失败',
      error: err.message
    })
  }
}

// 获取最近七日任务列表接口
exports.getRecentSevenDaysTasks = async (req, res) => {
  const { user_id } = req.query
  // 获取今天的日期，格式 YYYY-MM-DD
  const today = new Date().toISOString().split('T')[0]
  // 获取最近七天的日期，格式 YYYY-MM-DD
  const sevenDaysLater = new Date()
  sevenDaysLater.setDate(sevenDaysLater.getDate() + 7)
  const sevenDaysLaterStr = sevenDaysLater.toISOString().split('T')[0]
  console.log('今天日期:' + today)
  console.log('七天后的日期:' + sevenDaysLaterStr)
  const sql = 'SELECT * FROM task WHERE user_id = ? AND isDeleted = 0 AND finish_date BETWEEN ? AND ?'
  try {
    const result = await query(sql, [user_id, today, sevenDaysLaterStr])
    res.send({
      status: 0,
      message: '获取最近七日任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取最近七日任务列表失败',
      error: err.message
    })
  }
}

// 获取全部任务列表
exports.getAllTasks = async (req, res) => {
  const { user_id } = req.query
  console.log('获取全部任务列表的user_id:' + user_id)
  const sql = 'SELECT * FROM task WHERE user_id = ? AND isDeleted = 0'
  try {
    const result = await query(sql, [user_id])
    res.send({
      status: 0,
      message: '获取全部任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取全部任务列表失败',
      error: err.message
    })
  }
}

// 获取分类任务列表
exports.getTasksByClassification = async (req, res) => {
  const { user_id, classify_id } = req.query
  const sql = 'SELECT * FROM task WHERE user_id = ? AND isDeleted = 0 AND classify_id = ?'
  try {
    const result = await query(sql, [user_id, classify_id])
    console.log('获取动态分类任务列表result:', result + 'classify_id:' + classify_id + ' user_id:' + user_id)
    res.send({
      status: 0,
      message: '获取动态分类任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取动态分类任务列表失败',
      error: err.message
    })
  }
}

// 获取已完成任务列表
exports.getFinishedTasks = async (req, res) => {
  const { user_id } = req.query
  const sql = 'SELECT * FROM task WHERE user_id = ? AND isDeleted = 0 AND isFinished = 1'
  try {
    const result = await query(sql, [user_id])
    res.send({
      status: 0,
      message: '获取已完成任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取已完成任务列表失败',
      error: err.message
    })
  }
}

// 获取已删除任务列表
exports.getDeletedTasks = async (req, res) => {
  const { user_id } = req.query
  const sql = 'SELECT * FROM task WHERE user_id = ? AND isDeleted = 1'
  try {
    const result = await query(sql, [user_id])
    res.send({
      status: 0,
      message: '获取已删除任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取已删除任务列表失败',
      error: err.message
    })
  }
}

// 添加任务接口
exports.addTask = async (req, res) => {
  // 任务id默认自增,不需要传值
  const { user_id, title, classify_id, classify_name, isFinished, finish_date, create_date, isDeleted } = req.body
  const sql =
    'INSERT INTO task (user_id, title, classify_id, classify_name, isFinished, finish_date, create_date, isDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
  try {
    const result = await query(sql, [user_id, title, classify_id, classify_name, isFinished, finish_date, create_date, isDeleted])
    res.send({
      status: 0,
      message: '添加任务成功',
      data: {
        id: result.insertId,
        user_id,
        title,
        classify_id,
        classify_name,
        isFinished,
        finish_date,
        create_date,
        isDeleted
      }
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '添加任务失败',
      error: err.message
    })
  }
}

// 编辑任务接口(包括完成任务)
exports.editTask = async (req, res) => {
  const id = parseInt(req.params.id, 10)
  const { title, classify_id, classify_name, finish_date } = req.body
  console.log('res.params.id:' + req.params.id)
  console.log('编辑任务的id:' + id)
  console.log('编辑任务的title:' + title)
  console.log('编辑任务的classify_id:' + classify_id)
  console.log('编辑任务的classify_name:' + classify_name)
  console.log('编辑任务的finish_date:' + finish_date)
  const sql =
    'UPDATE task SET title = ?, classify_id = ?, classify_name = ?, finish_date = ? WHERE id = ?'
  try {
    const result = await query(sql, [title, classify_id, classify_name, finish_date, id])
    res.send({
      status: 0,
      message: '编辑任务成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '编辑任务失败',
      error: err.message
    })
  }
}

// 完成任务接口
exports.finishTask = async (req, res) => {
  const { id } = req.params
  const sql = 'UPDATE task SET isFinished = 1 WHERE id = ?'
  try {
    await query(sql, [id])
    res.send({
      status: 0,
      message: '完成任务成功'
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '完成任务失败',
      error: err.message
    })
  }
}

// 删除任务接口(软删除)
exports.deleteTask = async (req, res) => {
  const { id } = req.params
  const sql = 'UPDATE task SET isDeleted = 1 WHERE id = ?'
  try {
    await query(sql, [id])
    res.send({
      status: 0,
      message: '删除任务成功'
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '删除任务失败',
      error: err.message
    })
  }
}

// 删除任务接口(彻底删除)
exports.deleteTaskCompletely = async (req, res) => {
  const { id } = req.params
  const sql = 'DELETE FROM task WHERE id = ?'
  try {
    await query(sql, [id])
    res.send({
      status: 0,
      message: '彻底删除任务成功'
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '彻底删除任务失败',
      error: err.message
    })
  }
}

// 彻底删除所有垃圾桶内任务
exports.deleteAllSecondlyDeletedTasks = async (req, res) => {
  const { user_id } = req.query
  const sql = 'DELETE FROM task WHERE user_id = ? AND isDeleted = 1'
  try {
    await query(sql, [user_id])
    res.send({
      status: 0,
      message: '彻底删除所有垃圾桶内任务成功'
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '彻底删除所有垃圾桶内任务失败',
      error: err.message
    })
  }
}

// 按月份获取任务列表
exports.getTasksByMonth = async (req, res) => {
  const { user_id, month } = req.query // month 需要是 'YYYY-MM' 格式
  const sql = `SELECT * FROM task WHERE user_id = ? AND isDeleted = 0 AND DATE_FORMAT(finish_date, '%Y-%m') = ?`
  try {
    const result = await query(sql, [user_id, month])
    res.send({
      status: 0,
      message: '按月份获取任务列表成功',
      data: result
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '按月份获取任务列表失败',
      error: err.message
    })
  }
}


